from src.choice_api.utils import data_str2timestamp, sort_by_first_element


def parse_sludge_transport_record(data, target):
    if data is None or "list" not in data:
        return None

    if "in" in target:
        time_column = "timeIn"
    else:
        time_column = "timeOut"

    data_lst = data["list"]
    if not data_lst:
        data_lst = []

    # 真实要获取的字段
    columns_lst = ["weightIn", "weightOut", "sludgeWeight", "waterContent"]

    # 单表csv解析
    # res_columns = ["time"]
    # res_data = [[x["time"]] for x in company_lst[list(company_lst.keys())[0]]]
    #
    # for k, val_lst in company_lst.items():
    #     for param in columns_lst:
    #         res_columns.append(f"{k} {param_mapping[param]}")
    #         for idx, val in enumerate(val_lst):
    #             res_data[idx].append(val[param])
    # return {
    #     "res_columns": res_columns,
    #     "res_data": res_data,
    # }

    # 单表时序指标形式
    res_columns = []
    res_data = {}
    res_tip = []

    column_mapping = {
        "weightIn": "入库",
        "weightOut": "出库",
        "sludgeWeight": "重量",
        "waterContent": "含水量"
    }

    for row in data_lst:
        for column in columns_lst:
            if not row[column]:
                continue

            label = f"污泥{column_mapping[column]} 去向{row["destination"]}"
            if label not in res_columns:
                res_columns.append(label)
                res_data[label] = []

            res_data[label].append([data_str2timestamp(row[time_column]), row[column]])

    for column in res_columns:
        res_data[column] = sort_by_first_element(res_data[column])

    return {
        "res_columns": res_columns,
        "res_data": res_data,
        "res_tip": res_tip
    }
